#include <stdlib.h>
#include <sys/epoll.h>
#include <unistd.h>
#include <mysql/mysql.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <jwt.h>

#include "../include/threadPool.h"
#include "../include/error.h"
#include "../include/tlv.h"
#include "../include/ftp.h"

void taskHandle(int clientfd){
    uint32_t type;
    uint32_t length;
    uint8_t value[TLV_VALUE_MAX_SIZE];

    if(tlv_listen(clientfd,&type,&length,value)==-1){
        if(tlv_response(clientfd,RESPONSE_ERROR_REQUEST,0,NULL)==-1){printf("tlv_response error");}
        printf("tlv_listen error");
        return;
    }

    printf("Received TLV:\n");
    printf("Type: %u\n", type);
    printf("Length: %u\n", length);
    printf("Value: %s\n",value);
    if(type == REQUEST_PUTS){
        if(tlv_response(clientfd,RESPONSE_OK,0,NULL)==-1){printf("tlv_response error");}
        else{
            char file_path[1024];
            snprintf(file_path, sizeof(file_path), "./disk/%.41s", (char *)value);
            if(recv_file(clientfd,file_path)!=0){thread_perror("recv_file");}
        }
    }
    else if(type == REQUEST_GETS){
        if(tlv_response(clientfd,RESPONSE_OK,0,NULL)==-1){printf("tlv_response error");}
        else{
            char file_path[1024];
            snprintf(file_path, sizeof(file_path), "./disk/%.41s", (char *)value);
            if(send_file_fragment(clientfd,file_path)!=0){thread_perror("send_file");}
        }
    }
}



void unlock(void *arg){
    threadPool_t *pthreadPool = (threadPool_t *)arg;
    pthread_mutex_unlock(&pthreadPool->mutex);
}
void *threadFunc(void *arg){
    threadPool_t *pthreadPool = (threadPool_t *)arg;
    while(1){
        int netfd;
        pthread_mutex_lock(&pthreadPool->mutex);
        pthread_cleanup_push(unlock,pthreadPool);
        while(pthreadPool->taskQueue.queueSize == 0){
            pthread_cond_wait(&pthreadPool->cond,&pthreadPool->mutex);
        }
        netfd = pthreadPool->taskQueue.pFront->netfd;
        printf("I am worker, I got netfd = %d\n",netfd);
        deQueue(&pthreadPool->taskQueue);
        pthread_cleanup_pop(1);

        printf("I am worker doing something\n");

        //文件传输函数
        taskHandle(netfd);
        close(netfd);
    }
}

int makeWorker(threadPool_t *pthreadPool){
    for(int i = 0; i < pthreadPool->tidArr.workerNum;++i){
        pthread_create(&pthreadPool->tidArr.arr[i],NULL,threadFunc,pthreadPool);
    }
    return 0;
}
